var _gameManager;
var _gameMap;
var _gameToJoin = "";
var _enableAudio = false;

var _jqt = new $.jQTouch({
    icon: 'jqtouch.png',
    statusBar: 'black-translucent',
    preloadImages: [
        '/images/jqttheme/chevron.png',
        '/images/jqttheme/back_button_clicked.png',
        '/images/jqttheme/button_clicked.png'
        ]
});


$(document).ready(function(){
	_gameManager = new TLVIVI.Pacman.GameManager(showMessage);
	bindEvents();
});

function bindEvents(){
	$("#enableSound").bind("change", function(){
		_enableAudio = $(this).val();
	})
}

function initGameSelectionScreen(){
	_jqt.goTo("#gameSelectionScreen", "swap");
	
	_gameManager.getAllGames(function(result){
		var itemTemplate = "<li><span class='listItem'></span></li>";
		var listContainer = $("ul", $("#gameSelectionScreen"));
		listContainer.empty();
		
		$.each(result.Games, function(index, value){
			if (value.State == 0 || value.State == 1){
				var currGame = $(itemTemplate);
				
				$("span", currGame).bind('click', function(){_gameToJoin = value.Name; _jqt.goTo("#joinGameScreen", "swap")});
				$("span", currGame).text(value.Name);
				
				listContainer.append(currGame);
			}	
		});
	});
}


function initGameStateScreen(){
	var gameStatePanel = $("#gameStateScreen");
	$("ul", gameStatePanel).makePlayersList({gameManager:_gameManager, gameName:_gameManager.getCurrGameName()})
}


function createNewGame(){
	// check if the user filled a game name
	if ($("#txtGameName").val().length > 0){
		_gameToJoin = $("#txtGameName").val();
		_gameManager.createNewGame($("#txtGameName").val(), function(){});
		_jqt.goTo("#joinGameScreen", "swap");
	}
	else {
		alert ("You must fill a game name");
	}
}

function joinGame(){
	if ($(txtPlayerName).val().length > 0){
		var gameName = "";
		
		_gameManager.joinGame(_gameToJoin, $("#txtPlayerName").val(), $("#ddlPlayerRole").val(), onJoinGameBack);
		_jqt.goTo("#gameIntroScreen", "swap");
	}
	else {
		alert ("You must eneter a name");
		
	}
}

function onJoinGameBack(result){
	var gameIntroPanel = $("#gameIntroScreen");
	var gameName = _gameToJoin;
	$("h1", gameIntroPanel).text(gameName);
	
	$("ul", gameIntroPanel).makePlayersList({gameName: gameName, gameManager: _gameManager});
	
	// If the player is in Pacman role, allow him to start the game
	if ($("#ddlPlayerRole").val() == "1"){
		$("a", gameIntroPanel).toggleClass("hidden");
	}
	else {
		waitForGameStart(gameName);
	}
}

function waitForGameStart(gameName){
	_gameManager.getGameStatus(gameName, function(data){
		
		// if the game started
		if (data > 1){
			startGame();
			_jqt.goTo("#gameBoard", "cube");
		}
		else {
			var x = setTimeout(function(){waitForGameStart(gameName)}, 5000);
		}
	});
}

function startGame(){
	playSound("startGameAudio");
	setUpBoardGame();
	getGameState();
}

function setUpBoardGame(){
	_gameMap = new TLVIVI.Pacman.Map("mapCanvas");
	_gameMap.initMap(32.07579, 34.77995, 14);
}

function getGameState(){
	_gameManager.getGameState(function(result){
		_gameMap.drawGameBorder(_gameManager.getGameBorders());
		_gameMap.drawAllApples(_gameManager.getApples());
		updateGameState();
	});
}

function updateGameState(){
	navigator.geolocation.getCurrentPosition(function(position){
		_gameManager.updateGameState(position.coords.latitude, position.coords.longitude, true, 5, function(result){
			if (result.GameState == 4){
				playSound("gameOver");
			}
			else if (result.GameState == 2 || result.GameState == 5){
				_gameMap.updateRemovedApples(result.RemovedAppleIds);
				_gameMap.drawPlayers(_gameManager.getCurrGamePlayers(), result.GameState);
			}
			
			// show all returned messages
			$.each(result.RecentMessages, function(index, value){
				showMessage(value.Body, value.SenderName);
			})
			
			setTimeout(updateGameState, 5000);
		})
	})
}


function showMessage(message, sender){
	$("#messageBody").html(message);
	$("#messagesPanel").toggleClass("hidden");
	
	window.setTimeout(function(){
		$("#messagesPanel").toggleClass("hidden");
	}, 2000);
}


function sendMessage(){
	var messagePanel = $("#txtSendMessage");
	if (messagePanel.val().length > 0){
		_gameManager.sendMessage(messagePanel.val());
		messagePanel.text("");
	}
}

function playSound(soundId){
	if (_enableAudio){
		$('#' + soundId)[0].play();
	}
}
